﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

namespace ArchiveIISLogs
{
    public class LogFileDirectory
    {
        private const string AllZipFiles = @"*.zip";

        private DateTime Yesterday
        {
            get
            {
                return DateTime.Now.AddDays(-1);
            }
        }

        public List<FileInfo> GetWebsiteLogfileDirectories()
        {

            //grab a list of all the directories and files in the given dir.
            List<FileInfo> filesToCompress = new List<FileInfo>();
            List<FileInfo> allFiles = new List<FileInfo>();


            string logFileExtenstion = Config.GetFileExtensionToCompress();
            foreach (DirectoryInfo d in GetDirectoriesStartingWithName())
            {
                allFiles.AddRange(d.GetFiles(logFileExtenstion, SearchOption.AllDirectories));
            }

            //only want to compress those files that are older than 1 day
            filesToCompress.AddRange(allFiles.Where(x => x.LastWriteTime <= Yesterday));

            //write current status to the log
            AppLogger.LogMessage("Found {0} log files. {1} fit the critieria of being older than 1 day (i.e. not in use).".FormatWith(allFiles.Count, filesToCompress.Count));

            return filesToCompress;
        }

        public IEnumerable<DirectoryInfo> GetDirectoriesStartingWithName()
        {

            string machineLogDirectory = Config.GetMachineWebLogsDirectory();
            string websiteLogFilePrefix = Config.GetWebLogFilePrefix();

            DirectoryInfo systemLogDirectory = new DirectoryInfo(machineLogDirectory);

            foreach (var item in systemLogDirectory.GetDirectories(websiteLogFilePrefix, SearchOption.TopDirectoryOnly))
            {
                if (item.GetFiles().Any())
                {
                    yield return item;
                }
            }
        }

        public List<FileInfo> GetZipFilesInWebLogDirectory(DateTime olderThanDate)
        {
            string machineLogDirectory = Config.GetMachineWebLogsDirectory();
            string websiteLogFilePrefix = Config.GetWebLogFilePrefix();

            //grab a list of all the files in the given dir.
            DirectoryInfo systemLogDirectory = new DirectoryInfo(machineLogDirectory);
            FileInfo[] allZips = systemLogDirectory.GetFiles(AllZipFiles, SearchOption.TopDirectoryOnly);

            return new List<FileInfo>(allZips);
        }

        public void DeleteFile(FileInfo logFileToDelete)
        {
            try
            {
                logFileToDelete.Delete();
            }
            //todo: handle all these!
            catch (System.IO.IOException) { }
            catch (System.Security.SecurityException) { }
            catch (System.UnauthorizedAccessException) { }
        }
    }
}
